package com.ls.controller.logistic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ls.controller.logistic.model.AddLogisticModel;
import com.ls.controller.logistic.model.QueryLogisticModel;
import com.ls.controller.logistic.model.LogisticsSmsModel;
import com.ls.service.ILogisticService;
import com.ls.utils.ResultData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.UUID;

/**
 * <p>
 * 物流 前端控制器
 * </p>
 *
 * @author pengyu
 * @since 2024-10-12
 */
@Slf4j
@Api(value = "物流相关接口", tags = "物流相关接口")
@RestController
@RequiredArgsConstructor
@RequestMapping("/logistic")
public class LogisticController {
    private final ILogisticService service;
    /** 分页物流记录 */
    @GetMapping("pageList")
    public ResultData pageList(QueryLogisticModel model) {
        return service.pageList(model);
    }
    /**导入物流单号*/
    @PostMapping(value = "import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiOperation("物流数据导入")
    public ResultData importExcel(@RequestParam("file") MultipartFile file,@RequestParam("type") Integer type) {
        log.info("测试：{}",type);
        File tempFile = null;
        try {
            String tempFileName = System.getProperty("java.io.tmpdir")
                    + "logistic_import_" + UUID.randomUUID() + ".xlsx";
            tempFile = new File(tempFileName);

            log.info("临时文件:{}", tempFile.getAbsolutePath());
            // 直接写入目标文件（自动创建新文件）
            file.transferTo(tempFile);

            return service.analyseExcelLogistic(tempFile,type);
        } catch (IOException e) {
            log.error("文件传输失败 | 文件名:{} 大小:{}",
                    file.getOriginalFilename(), file.getSize(), e);
            return ResultData.failure("文件传输异常：" + e.getMessage());
        } catch (Exception e) {
            log.error("物流导入系统异常 | 临时文件:{}",
                    tempFile != null ? tempFile.getAbsolutePath() : "null", e);
            return ResultData.failure("系统处理异常：" + e.getMessage());
        } finally {
            // 强制删除临时文件（参考FileUtils实现）
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
        }
    }
    /** 发送物流短信 */
    @PostMapping("send")
    public ResultData send(@Valid @RequestBody LogisticsSmsModel model) {
        return service.send(model,0);
    }
    /** 查询物流轨迹 */
    @GetMapping("queryTrack")
    public ResultData queryTrack(String logisticNum) throws Exception {
        String rawResult = service.queryTrack(logisticNum);
        JSONObject resultJson = JSON.parseObject(rawResult);
        return ResultData.successData(resultJson);
    }
    /**获取物流状态*/
    @GetMapping("getStatus")
    public ResultData getStatus() {
        return service.getStatus();
    }
    /**单个添加物流单号*/
    @PostMapping("add")
    public ResultData add(@Valid @RequestBody AddLogisticModel model) {
        return service.add(model);
    }
}
